/** 文件写入内容是异步
 *  所以当文件没有写入完成又有写入请求时，缓存写入内容，当上一次写入内容完成时，将继续写入缓存的内容
 */
const { timeStamp } = require('console');
const fs = require('fs');
const path = require('path');
const logsFilepath = path.join(process.cwd(), '/logs');

module.exports = class Logger {
  static logFile
  static errorFile
  constructor(pathName = '') {
    this.pathName = pathName
    this.logcache = ''
    this.logStatus = true
    this.errorcache = ''
    this.errorStatus = true
    this.modifylogFile()
  }
  // 写入log
  log(content) {
    console.log(content)
    this.modifylogFile()
    this.logcache += content + '\n'
    if(!this.logStatus) return
    this.logStatus = false
    this.access(this.logFile, ()=>{
      fs.readFile(this.logFile, 'utf-8',(err, str)=>{
        if(err) {
          // 读取失败
        } else {
          const newtxt = str  + this.logcache
          this.logcache = ''
          this.writeFile(this.logFile, newtxt, ()=>{
            this.logStatus = true
            if (this.logcache) {
              this.log('')
            }
          })
        }
      });
    })
  }
  // 写入error
  error(content) {
    console.log(content)
    this.modifylogFile()
    this.errorcache += content + '\n'
    if(!this.errorStatus) return
    this.errorStatus = false
    this.access(this.errorFile, ()=>{
      fs.readFile(this.errorFile, 'utf-8',(err, str)=>{
        if(err) {
          // 读取失败
        } else {
          const newtxt = str  + this.errorcache
          this.errorcache = ''
          this.writeFile(this.errorFile, newtxt, ()=>{
            this.errorStatus = true
            if (this.errorcache) {
              this.log('')
            }
          })
        }
      });
    })
  }

  // 判断文件是否存在
  access(file, callback) {
    fs.access(file, fs.constants.F_OK, (err)=> {
      if (err) {
        // 不存在文件创建
        this.createMkdir(file, callback);
      } else {
        // 存在，直接写
        callback();
      }
    });
  }

  // 创建文件夹
  createMkdir(path, callback) {
    fs.mkdir(logsFilepath, (err) => {
      this.writeFile(path, '', callback)
    })
  }
  // 创建写入文件
  writeFile(path, content, callback) {
    fs.writeFile(path, content, { encoding: "utf8" }, (err) => {
      callback();
    })
  }
  // 更改文件名称时间
  modifylogFile () {
    const time = this.modifyTimeFile()
    this.logFile = path.join(logsFilepath + '/' + (this.pathName ? this.pathName + time + '-log.log' : time + 'log.log'))
    this.errorFile = path.join(logsFilepath + '/' + (this.pathName ? this.pathName + time + '-error.log' : time + 'error.log'))
  }
  // 时间计算
  modifyTimeFile () {
    const data = new Date()
    const year = data.getFullYear()
    const month = data.getMonth() + 1
    const day = data.getDate()
    return '-' + year + '-' + month + '-' + day
  }
}
